package com.wswy.wzcx.ui.car.choose

import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import com.che.libcommon.utils.optional.Optional
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.car.CarTypeData
import com.wswy.wzcx.model.car.CarTypeResp
import com.wswy.wzcx.module.base.BaseViewModel
import com.wswy.wzcx.module.base.Resource
import com.wswy.wzcx.module.base.onResult
import com.wswy.wzcx.utils.RxUtils
import io.reactivex.Single

class ChooseCarViewModel :BaseViewModel() {

    private val brands=MutableLiveData<Resource<List<CarTypeResp>>>()

    private val currentSeriesLiveData = MutableLiveData<String>()

    private val carSeries = MutableLiveData<Resource<List<CarTypeResp>>>()

    private val carModels = MutableLiveData<Resource<List<CarTypeResp>>>()

    val chooseCar = CarTypeData()



    fun loadBrands(){
        addRun(wrapApi(Api.get().carBrands()).onResult(brands))

    }

    fun getSeries(brandId:String){


        addRun(wrapApi(Api.get().carSeries(brandId)).onResult(carSeries))

    }

    fun getModels(seriesId:String){


        addRun(wrapApi(Api.get().carSpecification(seriesId)).onResult(carModels))
    }

    fun setSeries(seriesId: String){
        currentSeriesLiveData.postValue(seriesId)
    }

    fun getCurrentSeriesLiveData():LiveData<String> = currentSeriesLiveData

    fun getBrandsLiveData():LiveData<Resource<List<CarTypeResp>>> = brands

    fun getSeriesLiveData():LiveData<Resource<List<CarTypeResp>>> = carSeries

    fun getModelLiveData():LiveData<Resource<List<CarTypeResp>>> = carModels



    private fun wrapApi(request: Single<Optional<List<CarTypeResp>>>):Single<Optional<List<CarTypeResp>>>{
        return request.compose(RxUtils.switch2io()).map {
            it.orNull()?.forEachIndexed{index, carTypeResp ->
                carTypeResp.list?.forEach {
                    it.headerId = index.toLong()
                }
            }
            it
        }
    }

}